package com.anzhen.interview.xml.study;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Created by anzhen on 2017-4-27.
 */
public class MarshallerTest {
	public static void main(String[] args) throws JAXBException {
		marshall();

		unMarshal();
	}

	public static void marshall() throws JAXBException{
		Person person = new Person();
		person.setName("Zhangsan");
		person.setAge(11);

		JAXBContext context = JAXBContext.newInstance(Person.class);
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

		//将XML打印到控制台
		marshaller.marshal(person, System.out);

		//将XML输出到一个文件，以便后面进行反序列化
		try(FileOutputStream out = new FileOutputStream("person.xml")){
			marshaller.marshal(person, out);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public static void unMarshal() throws JAXBException{
		JAXBContext context = JAXBContext.newInstance(Person.class);
		Unmarshaller u = context.createUnmarshaller();

		try(FileInputStream in = new FileInputStream("person.xml")){
			Person person = (Person)u.unmarshal(in);
			System.out.println(person.getName() + " : " + person.getAge());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
